#!/usr/bin/env python
"""
Alfredo Deza @ 2009

Does not remove anything from the filesystem.
Everything is moved to the /tmp/ directory.
You will always be able to undelete stuff as long as it is still in /tmp/

"""

import shutil
from optparse import OptionParser
import sys
import os

class NeverDel(object):
    """Main class to perform all the actions for the file(s) """
    
    def __init__(self,
                 location='/tmp',
                 file_check=True,
                 path=None,
                 file_name=None,
                 metadata_file=None,
                 ):
        self.location = location
        if file_check:
            if not os.path.exists(path):
                message = "Invalid path or file: %s" % path
                err(message)
        self.path = os.path.abspath(path) # absolute path
        self.file_name = os.path.basename(self.path) # file name
        self.metadata_file = "%s/.%s" % (self.location, self.file_name)        

    def move(self):
        """Move the file to /tmp/"""
        message =  "mv %s to /tmp/" % self.path
        tmp_location = "/tmp/%s" % self.file_name
        self.metadata() # write the metadata file
        if os.path.isdir(tmp_location):
            os.rmdir(tmp_location)
        if os.path.isfile(tmp_location):
            os.remove(tmp_location)
        shutil.move(self.path, self.location) 
        out(message)
    
    def restore(self):
        """Restore the file from /tmp/ to its original location"""
        try:
            inread = open(self.metadata_file)
            old_path = inread.readline()
            tmp_location = "%s/%s" % (self.location, self.file_name)
            shutil.move(tmp_location, old_path)
            print "Restoring %s to %s" % (tmp_location, old_path)
            
        except IOError:
            error = """No metadata file found for: %s
Could not recover.""" % self.path
            err(error)
        
    def metadata(self):
        """Create a hidden metadata file"""
        inwrite = open(self.metadata_file, 'w')
        inwrite.write(self.path)
        inwrite.close()
        
def out(message):
    """Write to stdout explaining nothing was deleted"""
    sys.stdout.write(message+'\n')

def err(message):
    """Write to stderr the error message"""
    sys.stderr.write(message+'\n')
    sys.exit(1)

def main():
    """Create the CLI options and arguments to accept """
    arguments = sys.argv
    if len(arguments) >= 1:
        arguments.pop(0)
        for arg in arguments:

            if 'recover' in arguments[0]:
                arg_position = arguments[-1]
                action = NeverDel(file_check=False, path=arg_position)
                action.restore()
                break 
            
            if arg.startswith('-'):
                pass # any combination works

            else:
                action = NeverDel(path=arg)
                action.move()

if __name__ == '__main__':
    main()


